package org.sp1.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.sp1.dao.UserDao;
import org.sp1.model.SpUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

public class UserImpl implements UserDao {

	private JdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public SpUser findByUserName(final String userName) {
		// TODO 自动生成方法存根
		String sql = " SELECT user_id,user_name,credits "
				+ " FROM sp_user WHERE user_name =? ";
		final SpUser user = new SpUser();

		jdbcTemplate.query(sql, new Object[] { userName },
				new RowCallbackHandler() {

					public void processRow(ResultSet rs) throws SQLException {
						// TODO 自动生成方法存根
						user.setUserId(rs.getLong("user_id"));
						user.setUserName(userName);
						user.setCredits(rs.getLong("credits"));
					}

				});

		return user;
	}

	public int getMacthCount(String userName, String password) {
		// TODO 自动生成方法存根
		String sql = "SELECT count(*) FROM sp_user "
				+ " WHERE user_name =? and password=?  ";
		return jdbcTemplate.queryForInt(sql,
				new Object[] { userName, password });

	}

	public void updateLoginInfo(SpUser user) {
		// TODO 自动生成方法存根
		String sql = " UPDATE sp_user SET last_visit=?,last_ip=?,credits=? "
				+ " WHERE user_id =?";

		jdbcTemplate.update(sql, new Object[] { user.getLastVisit(),
				user.getLastIp(), user.getCredits(), user.getUserId() });
	}

}
